package cn.chiship.framework.upms.biz.system.controller;


import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.upms.biz.base.service.CacheService;
import cn.chiship.framework.upms.biz.system.entity.UpmsSystem;
import cn.chiship.framework.upms.biz.system.entity.UpmsSystemExample;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsSystemDto;
import cn.chiship.framework.upms.biz.system.service.UpmsSystemService;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.core.annotation.Authorization;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.base.constants.CacheConstants;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 系统控制层
 * 2021/9/27
 *
 * @author lijian
 */
@RestController
@Authorization
@RequestMapping("/system")
@Api(tags = "系统管理")
public class UpmsSystemController extends BaseController<UpmsSystem, UpmsSystemExample> {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsSystemController.class);

    @Resource
    private UpmsSystemService upmsSystemService;
    @Resource
    CacheService cacheService;
    @Resource
    RedisService redisService;

    @Override
    public BaseService getService() {
        return upmsSystemService;
    }

    @SystemOptionAnnotation(describe = "系统分页")
    @ApiOperation(value = "系统分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "title", value = "系统名称", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "systemType", value = "系统类型", dataTypeClass = Byte.class, paramType = "query"),

    })
    @GetMapping(value = "/page")
    public ResponseEntity<BaseResult> page(
            @RequestParam(required = false, defaultValue = "", value = "title") String title,
            @RequestParam(required = false, defaultValue = "", value = "systemType") Byte systemType) {
        UpmsSystemExample upmsSystemExample = new UpmsSystemExample();
        /**
         * 创造条件
         */
        UpmsSystemExample.Criteria criteria = upmsSystemExample.createCriteria();
        criteria.andIsDeletedEqualTo(BaseConstants.NO);
        if (!StringUtil.isNullOrEmpty(title)) {
            criteria.andTitleLike(title + "%");
        }
        if (!StringUtil.isNull(systemType)) {
            criteria.andSystemTypeEqualTo(systemType);
        }

        PageVo pageVo = super.page(upmsSystemExample);
        cacheService.cacheSystems();
        return super.responseEntity(BaseResult.ok(pageVo));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, describe = "保存系统")
    @ApiOperation(value = "保存系统")
    @PostMapping(value = "save")
    public ResponseEntity<BaseResult> save(@RequestBody @Valid UpmsSystemDto upmsSystemDto) {
        UpmsSystem upmsSystem = new UpmsSystem();
        BeanUtils.copyProperties(upmsSystemDto, upmsSystem);
        return super.responseEntity(super.save(upmsSystem));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "更新系统")
    @ApiOperation(value = "更新系统")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path"),
    })
    @PostMapping(value = "update/{id}")
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id, @RequestBody @Valid UpmsSystemDto upmsSystemDto) {
        UpmsSystem upmsSystem = new UpmsSystem();
        BeanUtils.copyProperties(upmsSystemDto, upmsSystem);
        upmsSystem.setId(id);
        return super.responseEntity(super.update(id, upmsSystem));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "删除系统数据")
    @ApiOperation(value = "删除系统数据")
    @PostMapping(value = "remove")
    public ResponseEntity<BaseResult> remove(@RequestBody @Valid List<String> ids) {
        UpmsSystemExample upmsSystemExample = new UpmsSystemExample();
        upmsSystemExample.createCriteria().andIdIn(ids);
        return super.responseEntity(super.remove(upmsSystemExample));
    }

    @ApiOperation(value = "加载系统列表")
    @GetMapping(value = "/loadSystem")
    public ResponseEntity<BaseResult> loadSystem() {
        Map<Object, Object> systemMap = redisService.hget(CommonCacheConstants.buildKey(CacheConstants.REDIS_SYSTEM_PREFIX));
        List<UpmsSystem> upmsSystems = new ArrayList<>();
        for (Map.Entry<Object, Object> entry : systemMap.entrySet()) {
            upmsSystems.add((UpmsSystem) entry.getValue());
        }
        upmsSystems.sort(new Comparator<UpmsSystem>() {
            @Override
            public int compare(UpmsSystem o1, UpmsSystem o2) {
                return o2.getOrders().compareTo(o1.getOrders());
            }
        });
        return super.responseEntity(BaseResult.ok(upmsSystems));
    }

    @SystemOptionAnnotation(describe = "根据编码获取系统")
    @ApiOperation(value = "根据编码获取系统")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "systemCode", value = "系统编码", required = true, dataTypeClass = String.class, paramType = "query")
    })
    @PostMapping(value = "getByCode")
    public ResponseEntity<BaseResult> getByCode(@RequestBody String systemCode) {
        UpmsSystem upmsSystem = (UpmsSystem) redisService.hget(CommonCacheConstants.buildKey(CacheConstants.REDIS_SYSTEM_PREFIX), systemCode);
        if (upmsSystem == null) {
            return super.responseEntity(BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_NO, null));
        }
        return super.responseEntity(BaseResult.ok(upmsSystem));
    }

}
